const Usecase = require('../../shared/usecase/Usecase')
const Menu = require('../../domain/menu/menu')
const { MenuCodeExistError } = require('../../domain/menu/error')

class CreateMenu extends Usecase {
  constructor({ menuRepo, database, currentUser }) {
    super()
    this.menuRepo = menuRepo
    this.sequelize = database.sequelize
    this.currentUser = currentUser
  }
  async _validate(entity) {
    await entity.validate()
    if (
      await this.menuRepo.findBySystemIdAndCode(entity.systemId, entity.code)
    ) {
      throw new MenuCodeExistError(entity.systemId, entity.code)
    }
  }
  async execute(data) {
    const menu = Menu.create(data)
    await this._validate(menu)
    const transaction = await this.sequelize.transaction()
    try {
      await this.menuRepo.create(menu, {
        transaction,
        currentUser: this.currentUser,
      })
      await transaction.commit()
      return menu
    } catch (error) {
      await transaction.rollback()
      throw error
    }
  }
}

module.exports = CreateMenu
